import * as YvanUI from 'yvan-ui-wotu'
import Dialog from "./dialog";

// @ts-ignore
const {lodash: _, Antd, React} = YvanUI
const {Layout, Menu, Dropdown, Input, Skeleton} = Antd
const {Header, Content, Footer, Sider} = Layout;
const moment = YvanUI.moment

interface Ref {
    grid1: YvanUI.Grid
    grid2: YvanUI.Grid
    grid3: YvanUI.Grid
}

function fmtDate(javaTimestamp) {
    if (!javaTimestamp) {
        return '';
    }
    var timestamp = moment(javaTimestamp);
    return timestamp.format('YYYY-MM-DD HH:mm:ss');
}

export class Recommend extends YvanUI.Scope<void, Ref> {

    main = this.$$({
        query1: {
            f1: '1',
        },
        query2: {
            cat1: '',
            cat2: '',
            cat3: ''
        },
        query3: {
            group_id: '',
            group_name: '',
            cat1: '',
            cat2: '',
            cat3: ''
        },
        grid2Checked:[],
        grid3Checked:[]
    })

    commanform = function (tab: 1 | 2) {
        const form: any =
            {
                view: 'form',
                items: [
                    {
                        view: "row",
                        items: [
                            {
                                view: 'col',
                                span: 6,
                                items: [
                                    {
                                        view: 'select',
                                        label: '前端一级',
                                        bind: tab === 1 ? 'main.query2.cat1' : 'main.query3.cat1',
                                        idField: 'id',
                                        labelField: 'text',
                                        onChange: (sender: YvanUI.Select, value) => {
                                            if (tab === 1) {
                                                this.main.query2.cat2 = ''
                                                this.main.query2.cat3 = ''
                                            } else {
                                                this.main.query3.cat2 = ''
                                                this.main.query3.cat3 = ''
                                            }

                                        },
                                        dataSource: {
                                            url: "/_yvanui/query",
                                            method: "post-json",
                                            params: {
                                                db: "master",
                                                limit: -1,
                                                limitOffset: 0,
                                                moduleId: "o2o",
                                                needCount: false,
                                                sqlId: tab === 1 ? "cat1" : "cat21",
                                            }
                                        },
                                        onDataSourceAfter: (sender: YvanUI.Grid, dataOrgin: any, raw: any, api: any, isExportData: boolean) => {
                                            return dataOrgin.data
                                        }
                                    }
                                ]
                            },
                            {
                                view: 'col',
                                span: 6,
                                items: [
                                    {
                                        view: 'select',
                                        label: '前端二级',
                                        bind: tab === 1 ? 'main.query2.cat2' : 'main.query3.cat2',
                                        idField: 'id',
                                        labelField: 'text',
                                        onChange: (sender: YvanUI.Select, value) => {
                                            if (tab === 1) {
                                                this.main.query2.cat3 = ''
                                            } else {
                                                this.main.query3.cat3 = ''
                                            }

                                        },
                                        dataSource: {
                                            url: "/_yvanui/query",
                                            method: "post-json",
                                            params: {
                                                db: "master",
                                                limit: -1,
                                                limitOffset: 0,
                                                moduleId: "o2o",
                                                needCount: false,
                                                params: {
                                                    $watch: () => {
                                                        if (tab === 1) {
                                                            return this.main.query2.cat1
                                                        }
                                                        return this.main.query3.cat1
                                                    },
                                                    $then: (v) => {
                                                        if (v.length <= 0) {
                                                            return {}
                                                        }
                                                        if (tab === 1) {
                                                            return {
                                                                query2: {
                                                                    cat1: v
                                                                }
                                                            }
                                                        }
                                                        return {
                                                            query3: {
                                                                cat1: v
                                                            }
                                                        }
                                                    },
                                                },
                                                sqlId: tab === 1 ? "cat2" : "cat22",
                                            }
                                        },
                                        onDataSourceAfter: (sender: YvanUI.Grid, dataOrgin: any, raw: any, api: any, isExportData: boolean) => {
                                            return dataOrgin.data
                                        }
                                    }
                                ]
                            },
                            {
                                view: 'col',
                                span: 6,
                                items: [
                                    {
                                        view: 'select',
                                        label: '前端三级',
                                        bind: tab === 1 ? 'main.query2.cat3' : 'main.query3.cat3',
                                        idField: 'id',
                                        labelField: 'text',
                                        dataSource: {
                                            url: "/_yvanui/query",
                                            method: "post-json",
                                            params: {
                                                db: "master",
                                                limit: -1,
                                                limitOffset: 0,
                                                moduleId: "o2o",
                                                needCount: false,
                                                params: {
                                                    $watch: () => {
                                                        if (tab === 1) {
                                                            return this.main.query2.cat2
                                                        }
                                                        return this.main.query3.cat2
                                                    },
                                                    $then: (v) => {
                                                        if (v.length <= 0) {
                                                            return {}
                                                        }
                                                        if (tab === 1) {
                                                            return {
                                                                query2: {
                                                                    cat2: v
                                                                }
                                                            }
                                                        }
                                                        return {
                                                            query3: {
                                                                cat2: v
                                                            }
                                                        }

                                                    },
                                                },
                                                sqlId: tab === 1 ? "cat3" : "cat23",
                                            }
                                        },
                                        onDataSourceAfter: (sender: YvanUI.Grid, dataOrgin: any, raw: any, api: any, isExportData: boolean) => {
                                            return dataOrgin.data
                                        }
                                    }
                                ]
                            },
                            {
                                view: 'col',
                                span: 2,
                                items: [
                                    {
                                        view: 'button',
                                        text: '查询',
                                        onClick: () => {
                                            if (tab === 1) {
                                                this.refs.grid2.refresh();
                                            } else {
                                                this.refs.grid3.refresh();
                                            }
                                        }
                                    }
                                ]
                            }
                        ]
                    },
                ]
            };
        if (tab === 1) {
            const me = this;
            form.items[0].items.push({
                view: 'col',
                span: 2,
                items: [
                    {
                        view: 'button',
                        text: '新增',
                        onClick: () => {
                            new Dialog({isNew: true,callBack: ()=>{me.refs.grid2.refresh()}}).showDialog();
                        }
                    }
                ]
            },);
            form.items.push(<li>列表中关联为单向关联</li>)
            form.items.push(<li>导入时，某一前端三级分类数据处理为覆盖更新（即：该前端三级分类关联的数据，以本次导入为准）</li>)
            form.items.push(<li>某个前端三级分类，关联多个相关分类，在导入模板中体现为多条数据，在列表中展示为一条</li>)
        } else {
            form.items.splice(0, 0, {
                view: 'row',
                items: [
                    {
                        view: 'col',
                        span: 6,
                        items: [
                            {
                                view: 'text',
                                label: '套餐ID',
                                bind: 'main.query3.group_id',
                            }
                        ]
                    },
                    {
                        view: 'col',
                        span: 6,
                        items: [
                            {
                                view: 'text',
                                label: '套餐名称',
                                bind: 'main.query3.group_name',
                            }
                        ]
                    }
                ]
            })
        }
        return form
    }

    page1 = {
        title: '推荐权重配置',
        content: {
            view: 'card',
            items: [
                {
                    view: 'form',
                    items: [
                        {
                            view: 'select',
                            label: '推荐栏目',
                            idField: 'id',
                            labelField: 'text',
                            bind: "main.query1.f1",
                            data: [
                                {id: '1', text: '购物车-你可能还需要'},
                                {id: '2', text: '商品详情页-为您推荐'},
                                {id: '3', text: '商品详情页-品牌专区'}
                            ]
                        },
                        <span>注：描述中的“母品”，指各栏目推荐所依据的商品（如：购物车中母品为购物车中所有商品、商品详情页中母品为当前查看的商品）</span>,
                    ]
                },
                {
                    view: 'grid',
                    ref: 'grid1',
                    columns: [
                        {field: 'dimen_name', title: '维度', width: 155},
                        {field: 'description', title: '描述', width: 600},
                        {
                            field: 'weight', title: '权重', editMode: 'number', editable: true,
                            width: 60,
                            editParams: {
                                precision: 2
                            }
                        },
                        {field: 'update_time', title: '操作时间', formatter: 'fmtDate', width: 130},
                        {field: 'update_user', title: '操作人', width: 70}
                    ],
                    onCellEditingStopped: (sender, params)=>{
                        const {data} = params;
                        // @ts-ignore
                        YvanUI.ajax({url: "/_yvanui/execute", method: 'post-json', data:
                                {
                                    params: data,
                                    db: 'master',
                                    sqlId: 'dimension_update',
                                    moduleId: 'o2o'
                                }
                        }).then(res=>{
                            this.refs.grid1.refresh();
                            YvanUI.showInfo("修改成功！")
                        })
                    },
                    pagination: false,
                    dataSource: {
                        url: "/_yvanui/query",
                        method: "post-json",
                        params: {
                            db: "master",
                            filterModel: {},
                            limit: 0,
                            limitOffset: 100,
                            moduleId: "o2o",
                            needCount: true,
                            orderByModel: [],
                            params: {
                                $watch: () => this.main.query1.f1,
                                $then: (v) => {
                                    return {
                                        query1: {
                                            column_type: v
                                        }
                                    }
                                },
                            },
                            sqlId: "dimension"
                        }
                    },
                    onDataSourceAfter: (sender: YvanUI.Grid, dataOrgin: any, raw: any, api: any, isExportData: boolean) => {
                        return dataOrgin.data
                    }
                }
            ]
        }
    }

    page2 = {
        title: '三级分类相关配置',
        content: {
            view: 'card',
            items: [
                this.commanform(1),
                {
                    view: 'grid',
                    ref: 'grid2',
                    checkbox: true,
                    idField: 'id',
                    toolbar: [
                        // {
                        //     view: 'button',
                        //     text: '导入',
                        //     onClick: () => {
                        //         debugger
                        //     }
                        // },
                        // {
                        //     view: 'button',
                        //     text: '下载模版',
                        //     onClick: () => {
                        //         debugger
                        //     }
                        // },
                        {
                            view: 'button',
                            text: '批量删除',
                            onClick: () => {
                                const me = this;
                                const ids: string[] = [];
                                _.forEach(this.main.grid2Checked, (v)=>{
                                    ids.push(v.id);
                                })
                                if (_.size(ids) <= 0) {
                                    YvanUI.showError('请勾选要删除的数据');
                                    return;
                                }

                                YvanUI.confirm('确定要删除这' + _.size(ids) + '条数据?')
                                    .then(function () {
                                        debugger
                                        // @ts-ignore
                                        YvanUI.ajax({url: "/_yvanui/execute", method: 'post-json', data:
                                                {
                                                    params: { ids: ids },
                                                    db: 'master',
                                                    sqlId: 'correlation_delete',
                                                    moduleId: 'o2o'
                                                }
                                        }).then(res=>{
                                            YvanUI.showInfo('删除成功');
                                            me.refs.grid2.refresh()
                                        })
                                    });
                            }
                        }
                    ],
                    pagination: false,
                    columns: [
                        {field: 'id', hidden: true},
                        {
                            view: 'checkbox',
                            title: '勾选',
                            bind: 'main.grid2Checked',
                            checkboxDisabled: (param: YvanUI.IGridCellRenderParam) => {
                                return param.data.industryclass === '2'
                            },
                            onCheckboxChange: (param: YvanUI.IGridCellRenderParam) => {
                                console.log(param)
                            }
                        },
                        {field: 'front_name', title: '前端三级分类'},
                        {field: 'correlation_name', title: '相关三级分类', width: 500},
                        {field: 'update_time', title: '操作时间'},
                        {field: 'update_user', title: '操作人'},
                        {
                            title: '操作',
                            resizable: false,
                            suppressAutoSize: true,
                            suppressSizeToFit: true,
                            // pinned: 'right',
                            width: 120,
                            render: (param: YvanUI.IGridCellRenderParam) => {
                                const {data} = param
                                const me = this;
                                return [
                                    {
                                        view: 'button',
                                        text: '编辑',
                                        type: 'link',
                                        size: 'small',
                                        onClick: () => {
                                            new Dialog({ isNew: false,rowData:data, callBack: ()=>{me.refs.grid2.refresh()}}).showDialog();
                                        },
                                    }
                                ]
                            }
                        },
                    ],
                    dataSource: {
                        url: "/_yvanui/query",
                        method: "post-json",
                        params: {
                            db: "master",
                            moduleId: "o2o",
                            params: {
                                $watch: () => [this.main.query2.cat1, this.main.query2.cat2, this.main.query2.cat3],
                                $then: (arr) => {
                                    return {
                                        cat1: arr[0],
                                        cat2: arr[1],
                                        cat3: arr[2],
                                    }
                                }
                            },
                            sqlId: "correlation"
                        }
                    },
                    onDataSourceAfter: (sender: YvanUI.Grid, dataOrgin: any, raw: any, api: any, isExportData: boolean) => {
                        var data = dataOrgin.data;
                        var result = [];

                        //========== group by "front_class"
                        _.each(data, function (item) {
                            var result_item = _.find(result, function (i) {
                                return i.front_class === item.front_class;
                            });
                            var correlation_dict_item = _.find(window['dictMap'].catsMap, function (i) {
                                return _.toString(i.id) === _.toString(item.correlation_class);
                            });

                            var levelKey = item.correlation_class;
                            var levelValue = "";
                            if (correlation_dict_item) {
                                // 中西药品-风湿骨科-肩周炎 => 中西药品, 风湿骨科, 肩周炎
                                var correlation_dict_item_array = correlation_dict_item.text.split('-');

                                // 中西药品-风湿骨科: 肩周炎
                                levelKey = correlation_dict_item_array.slice(0, 2).join('-');
                                levelValue = correlation_dict_item_array[2];
                            }

                            if (result_item) {
                                //已经有这个前端分类, 吧"相关分类"的数据, 合并二级
                                if (_.has(result_item.correlation_tree, levelKey)) {
                                    result_item.correlation_tree[levelKey].push(levelValue);
                                } else {
                                    result_item.correlation_tree[levelKey] = [levelValue];
                                }

                            } else {
                                //没有这个前端分类，添加
                                var front_dict_item = _.find(window['dictMap'].catsMap, function (i) {
                                    return _.toString(i.id) === _.toString(item.front_class);
                                });

                                result_item = {
                                    id: item.front_class,
                                    front_class: item.front_class,
                                    front_name: front_dict_item ? front_dict_item.text : item.front_class,
                                    correlation_tree: {},
                                    update_time: item.update_time,
                                    update_user: item.update_user
                                };
                                result_item.correlation_tree[levelKey] = [levelValue];
                                result.push(result_item);
                            }

                        });

                        //========== format "correlation_class"
                        _.each(result, function (result_item) {
                            var sb = [];
                            _.forOwn(result_item.correlation_tree, function (value, key) {
                                sb.push(key + '-' + value.join('/'));
                            });
                            result_item.correlation_name = sb.join(',');
                        });

                        result.sort(function (o) {
                            return _.toInteger(moment(o.update_time).format('X'));
                        });
                        return result
                    }
                }
            ]
        }
    }

    page3 = {
        title: '运营主推品设置',
        content: {
            view: 'card',
            items: [
                this.commanform(2),
                {
                    view: 'grid',
                    ref: 'grid3',
                    pagination: false,
                    toolbar: [
                        // {
                        //     view: 'button',
                        //     text: '导入',
                        //     onClick: () => {
                        //         debugger
                        //     }
                        // },
                        // {
                        //     view: 'button',
                        //     text: '下载模版',
                        //     onClick: () => {
                        //         debugger
                        //     }
                        // },
                        {
                            view: 'button',
                            text: '批量删除',
                            onClick: () => {
                                const me = this;
                                const ids: string[] = [];
                                _.forEach(this.main.grid3Checked, (v)=>{
                                    ids.push(v.id);
                                })
                                if (_.size(ids) <= 0) {
                                    YvanUI.showError('请勾选要删除的数据');
                                    return;
                                }

                                YvanUI.confirm('确定要删除这' + _.size(ids) + '条数据?')
                                    .then(function () {
                                        debugger
                                        // @ts-ignore
                                        YvanUI.ajax({url: "/_yvanui/execute", method: 'post-json', data:
                                                {
                                                    params: { ids: ids },
                                                    db: 'master',
                                                    sqlId: 'promote_delete',
                                                    moduleId: 'o2o'
                                                }
                                        }).then(res=>{
                                            YvanUI.showInfo('删除成功');
                                            me.refs.grid3.refresh()
                                        })
                                    });
                            }
                        }
                    ],
                    idField: 'id',
                    columns: [
                        {field: 'id', hidden: true},
                        {
                            view: 'checkbox',
                            title: '勾选',
                            bind: 'main.grid3Checked',
                            checkboxDisabled: (param: YvanUI.IGridCellRenderParam) => {
                                return param.data.industryclass === '2'
                            },
                            onCheckboxChange: (param: YvanUI.IGridCellRenderParam) => {
                                console.log(param)
                            }
                        },
                        {field: '套餐id', title: '套餐ID', width: 120},
                        {field: '套餐名', title: '套餐名', width: 200},
                        {field: '主商品', title: '主商品', width: 120},
                        {field: '主商品编码', title: '主商品编码', width: 150},
                        {field: '套餐规格', title: '套餐规格', width: 200},
                        {field: '销售价', title: '销售价', width: 130},
                        {field: '销售状态', title: '销售状态', width: 130},
                        {field: '质检状态', title: '质检状态', width: 130},
                        {field: '返利金额', title: '返利金额', width: 130},
                        {field: '毛利额', title: '毛利额', width: 120},
                        {field: '毛利率', title: '毛利率', width: 120},
                        {field: '库存', title: '库存', width: 120},
                        {field: '导入时间', title: '导入时间', formatter: fmtDate},
                        {field: '导入人', title: '导入人'}
                    ],
                    dataSource: {
                        url: "/_yvanui/query",
                        method: "post-json",
                        params: {
                            db: "master",
                            moduleId: "o2o",
                            params: {
                                $watch: () => [this.main.query3.group_id, this.main.query3.group_name, this.main.query3.cat1, this.main.query3.cat2, this.main.query3.cat3],
                                $then: (arr) => {
                                    return {
                                        query3: {
                                            group_id: arr[0],
                                            group_name: arr[1],
                                            cat1: arr[2],
                                            cat2: arr[3],
                                            cat3: arr[4],
                                        }
                                    }
                                }
                            },
                            sqlId: "promote"
                        }
                    },
                    onDataSourceAfter: (sender: YvanUI.Grid, dataOrgin: any, raw: any, api: any, isExportData: boolean) => {
                        var data = dataOrgin.data;
                        var result = [];

                        return data
                    }
                }
            ]
        }
    }

    vjson = {
        view: 'tabs',
        defaultTabIndex: 1,
        items: [
            this.page1,
            this.page2,
            this.page3
        ]
    }

}